package com.treasure.infrastructure.index.impl;

import com.treasure.infrastructure.index.IndexDocHandler;
import com.treasure.infrastructure.index.IndexDocTypeEnum;
import com.treasure.infrastructure.index.loader.ESSegmentLoader;
import com.treasure.infrastructure.model.FileSegmentBean;
import com.treasure.common.model.UploadDocumentRequest;
import com.treasure.infrastructure.model.doc.SegmentESDocBean;
import com.treasure.infrastructure.repository.extraction.elastic.SegmentESDocRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;


@Service("indexESDoc")
public class IndexESDocHandlerImpl extends ESSegmentLoader implements IndexDocHandler {

    @Autowired(required = false)
    private SegmentESDocRepository segmentESDocRepository;

    @Override
    public IndexDocTypeEnum getIndexDocType() {
        return IndexDocTypeEnum.INDEX_ES_DOC;
    }

    @Override
    public void indexResourceSegment(String organizationCode, List<String> resourcePaths) throws IOException {
        List<FileSegmentBean> resourceSegmentBeans = loadSegmentList(resourcePaths);

        List<SegmentESDocBean> indexSegmentDocList = new ArrayList<>(resourceSegmentBeans.size() * 5);
        Date now = new Date();
        for (FileSegmentBean resourceSegmentBean : resourceSegmentBeans) {
            String segmentFirst = resourceSegmentBean.getSegmentList().stream().findFirst().orElse(null);
            if (Objects.isNull(segmentFirst)) continue;
            for (String segmentText : resourceSegmentBean.getSegmentList()) {
                SegmentESDocBean segmentDocBean = new SegmentESDocBean();
                segmentDocBean.setId(System.nanoTime());
                segmentDocBean.setDocName(resourceSegmentBean.getFileName());
                segmentDocBean.setOrganizationCode(organizationCode);
                // 段落首句视为摘要
                segmentDocBean.setSummaries(segmentFirst);
                segmentDocBean.setPassages(segmentText);
                segmentDocBean.setCreateTime(now);
                indexSegmentDocList.add(segmentDocBean);
            }
        }

        segmentESDocRepository.indexSegmentDoc(indexSegmentDocList);
    }

    @Override
    public void indexResourceSegment(UploadDocumentRequest uploadDocumentRequest, List<FileSegmentBean> fileSegmentBeanList) {

    }

}
